Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.IO
Imports System.Windows.Forms
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Collections
Imports System.Data.SqlClient
Imports CrystalDecisions.ReportSource
Imports DevExpress.XtraEditors

Public Class frmUtilityCRViewer
    Public myReport As ReportDocument
    Private mySubReport As ReportDocument
    Private mblnActivate As Boolean

    Public Sub callActivate()
        Call frmUtilityCRViewer_Activated(Nothing, Nothing)
    End Sub
    ''' <summary>
    ''' This method configure crystal report and generate
    ''' ************************IMPORTANT***********************************************
    ''' THE ORDER OF THE TABLE IN DATASET SHOULD BE SAME AS THE ORDER FOR MAIN REPORT AND SUBREPORT, 
    ''' 0 FOR MAIN REPORT, 
    ''' 1... ONWORDS FOR SUBREPORTS, 
    ''' ************************IMPORTANT***********************************************
    ''' </summary>
    ''' <param name="SendToPrinter">This is for directly send to printer</param>
    ''' <remarks></remarks>
    Public Sub ConfigureCrystalReports(ByVal listParams As SortedList, ByVal dsReport As DataSet, Optional ByVal SendToPrinter As Boolean = True)
        Try
            Dim mPath As String = Application.StartupPath & "\Reports\" & listParams("ReportName")

            myReport = New ReportDocument()

            'Sub report 
            Dim subReport As ReportDocument

            'Dim subReport123 As ReportDocument
            'Dim subReportObj As SubreportObject
            'Dim subReportO As SubreportObject

            If Not File.Exists(mPath) Then
                MessageBox.Show("Report path not found !", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            myReport.Load(mPath)

            'For Each subReport In myReport.Subreports 'Loop through Sub Reports for ASSIGNING DATA TO SUB REPORT
            '    Dim strSubReportName As String = subReport.Name
            '    subReport.SetDataSource(dsReport.Tables(strSubReportName))
            'Next



            For Each subReport In myReport.Subreports 'Loop through Sub Reports for ASSIGNING DATA TO SUB REPORT
                Dim strSubReportName As String = subReport.Name
                If dsReport.Tables.Contains(strSubReportName) Then
                    subReport.SetDataSource(dsReport.Tables(strSubReportName))
                Else
                    'subReport.Close()
                    'subReport.Load(Application.StartupPath & "\Reports\RptHeader.rpt")
                    'subReport.FileName = Application.StartupPath & "\Reports\RptHeader.rpt"
                End If
            Next


            'For Each subReport In myReport.Subreports 'Loop through Sub Reports for ASSIGNING DATA TO SUB REPORT
            '    Dim strSubReportName As String = subReport.Name
            '    subReportObj = myReport.ReportDefinition.ReportObjects.Item(strSubReportName)
            '    subReport123 = New ReportDocument()
            '    subReport123 = subReportObj.OpenSubreport(subReportObj.SubreportName)
            '    subReport123.SetDataSource(dsReport.Tables(strSubReportName))
            'Next

            myReport.SetDataSource(dsReport.Tables(0))      'ASSIGNING DATA TO MAIN REPORT

            crViewer.DisplayToolbar = True
            crViewer.DisplayGroupTree = False
            'crViewer.DisplayBackgroundEdge = True
            'crViewer.EnableDrillDown = False
            crViewer.ShowGroupTreeButton = False

            With myReport.DataDefinition 'Formula Feilds For Main Report
                For intX As Integer = 0 To .FormulaFields.Count - 1
                    If .FormulaFields(intX).Name = "SoftwareName" Then
                        .FormulaFields("SoftwareName").Text = TranslateStringToCRFormula(listParams("SoftwareName"))
                    ElseIf .FormulaFields(intX).Name = "DoctorName" Then
                        .FormulaFields("DoctorName").Text = "'" & listParams("DoctorName") & "'"
                    ElseIf .FormulaFields(intX).Name = "VisitDate" Then
                        .FormulaFields("VisitDate").Text = "'" & listParams("VisitDate") & "'"
                    ElseIf .FormulaFields(intX).Name = "DateHeader" Then
                        .FormulaFields("DateHeader").Text = "'" & listParams("DateHeader") & "'"
                    ElseIf .FormulaFields(intX).Name = "IsStatus" Then
                        .FormulaFields("IsStatus").Text = listParams("IsStatus")
                    ElseIf .FormulaFields(intX).Name = "RepHeader" Then
                        .FormulaFields("RepHeader").Text = "'" & listParams("RepHeader") & "'"
                    ElseIf .FormulaFields(intX).Name = "PatientName" Then
                        .FormulaFields("PatientName").Text = "'" & listParams("PatientName") & "'"
                    ElseIf .FormulaFields(intX).Name = "PatientAddress" Then
                        .FormulaFields("PatientAddress").Text = TranslateStringToCRFormula(listParams("PatientAddress"))
                    ElseIf .FormulaFields(intX).Name = "DOB" Then
                        .FormulaFields("DOB").Text = "'" & listParams("DOB") & "'"
                    ElseIf .FormulaFields(intX).Name = "Age" Then
                        .FormulaFields("Age").Text = "'" & listParams("Age") & "'"
                    ElseIf .FormulaFields(intX).Name = "DoctorNameWithQualification" Then
                        .FormulaFields("DoctorNameWithQualification").Text = "'" & listParams("DoctorNameWithQualification") & "'"
                    ElseIf .FormulaFields(intX).Name = "DateRangeHeader" Then
                        .FormulaFields("DateRangeHeader").Text = "'" & listParams("DateRangeHeader") & "'"
                    ElseIf .FormulaFields(intX).Name = "TotalPayment" Then
                        .FormulaFields("TotalPayment").Text = "'" & listParams("TotalPayment") & "'"
                    ElseIf .FormulaFields(intX).Name = "TotalBalance" Then
                        .FormulaFields("TotalBalance").Text = "'" & listParams("TotalBalance") & "'"
                        'ElseIf .FormulaFields(intX).Name = "TotalBalance" Then
                        '    .FormulaFields("TotalBalance").Text = "'" & listParams("TotalBalance") & "'"
                    End If
                Next
            End With
          
            For Each subReport In myReport.Subreports 'Formula Feilds For Sub Report

                With subReport.DataDefinition
                    For intX As Integer = 0 To .FormulaFields.Count - 1
                        If .FormulaFields(intX).Name = "DateHeader" Then
                            .FormulaFields("DateHeader").Text = "'" & listParams("DateHeaderSub") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderDoctorName" Then
                            .FormulaFields("HeaderDoctorName").Text = "'" & listParams("HeaderDoctorName") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderCompanyName" Then
                            .FormulaFields("HeaderCompanyName").Text = "'" & listParams("HeaderCompanyName") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderAddress1" Then
                            .FormulaFields("HeaderAddress1").Text = "'" & listParams("HeaderAddress1") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderAddress2" Then
                            .FormulaFields("HeaderAddress2").Text = "'" & listParams("HeaderAddress2") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderAddress3" Then
                            .FormulaFields("HeaderAddress3").Text = "'" & listParams("HeaderAddress3") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderContactDetails" Then
                            .FormulaFields("HeaderContactDetails").Text = "'" & listParams("HeaderContactDetails") & "'"
                        ElseIf .FormulaFields(intX).Name = "HeaderMailId" Then
                            .FormulaFields("HeaderMailId").Text = "'" & listParams("HeaderMailId") & "'"
                        End If
                    Next
                End With
            Next

            crViewer.ReportSource = Nothing
            crViewer.ReportSource = myReport

            If SendToPrinter = True Then
                myReport.PrintToPrinter(1, False, 1, 1)
            Else
                crViewer.Show()
                crViewer.Zoom(1)
            End If


        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            Me.Close()
            GC.Collect()
        End Try
    End Sub

    Private Function TranslateStringToCRFormula(ByVal VBString As String) As String

        Dim Returnstring As String = "'"

        'Split the string at every LF
        For Each SubString As String In VBString.Split(Chr(10))

            'Trim all the CR / LF characters
            SubString = SubString.Trim(vbCrLf.ToCharArray)

            'Form your string to the compatible CR Formula format. Chr(10) &nd Chr(13) should be inserted as a string, not as values!!
            If Returnstring = "'" Then
                Returnstring = Returnstring & SubString
            Else
                Returnstring = Returnstring & "' & Chr(10) & Chr(13) & '" & SubString
            End If
        Next

        Returnstring = Returnstring & "'"

        Return Returnstring

    End Function

    Private Sub frmUtilityCRViewer_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Me.StartPosition = FormStartPosition.CenterScreen

        If mblnActivate = True Then
            mblnActivate = False
            'Dim intX As Integer = Screen.PrimaryScreen.Bounds.Width
            'Dim intY As Integer = Screen.PrimaryScreen.Bounds.Height
            'Me.Height = intY - 100
            'Me.Width = intX - 30
            'Me.StartPosition = FormStartPosition.CenterScreen

            Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            For Each ctrl As Control In crViewer.Controls
                If TypeOf ctrl Is Windows.Forms.ToolStrip Then
                    Dim btnNew As New ToolStripButton
                    btnNew.Name = "Minimize"
                    btnNew.Image = mdiMain.imgEditIcons.Images(30)
                    btnNew.ToolTipText = "Minimize"
                    btnNew.Font = fnBold
                    btnNew.ForeColor = Color.Red
                    CType(ctrl, ToolStrip).Items.Add(btnNew)
                    AddHandler btnNew.Click, AddressOf DoWork
                  
                    Dim btnNew2 As New ToolStripButton
                    btnNew2.Name = "Close"
                    btnNew2.Image = mdiMain.imgEditIcons.Images(8)
                    btnNew2.ToolTipText = "Close"
                    btnNew2.Font = fnBold
                    btnNew2.ForeColor = Color.Red
                    CType(ctrl, ToolStrip).Items.Add(btnNew2)
                    AddHandler btnNew2.Click, AddressOf DoWork2
                    Exit For

                End If
            Next
        End If
    End Sub

    Private Sub DoWork(ByVal sender As Object, ByVal e As System.EventArgs)
        If sender.Name = "Minimize" Then
            Me.Text = "Double Click to Maximize the Report"
            Me.WindowState = FormWindowState.Minimized
            Me.BringToFront()

        Else
            lblReportCaption.Text = Me.Text
        End If
    End Sub

    Private Sub DoWork2(ByVal sender As Object, ByVal e As System.EventArgs)
        If sender.Name = "Close" Then
            Me.Close()
        End If
    End Sub

    Private Sub frmUtilityCRViewer_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        crViewer.Dispose()
        Me.Dispose()
        GC.Collect()
    End Sub

    Private Sub frmUtilityCRViewer_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then Me.Close()
    End Sub

    Private Sub frmUtilityCRViewer_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        mblnActivate = True
        lblReportCaption.Text = Me.Text

    End Sub
End Class